package service

import (
	"context"
	"time"

	"github.com/xuri/excelize/v2"
	"zhonghui/console/structs"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/logx"
	"zhonghui/console/warehouse/servicex"
)

func ParseImportPolicy(c context.Context, ossObject string) ([]structs.InsurePolicyData, error) {
	oc, err := servicex.OssClient("normal")
	if err != nil {
		logx.ZapTrace(c).Errorw("获取oss客户端失败", "err", err)
		return nil, err
	}
	s, err := oc.OssDownloadStream(ossObject)
	if err != nil {
		logx.ZapTrace(c).Errorw("解析文件失败", "err", err)
		return nil, err
	}

	data := make([]structs.InsurePolicyData, 0)

	f, err := excelize.OpenReader(s)
	defer f.Close()

	rows, err := f.GetRows("北京众惠保")
	if err != nil {
		logx.ZapTrace(c).Errorw("解析表格出错", "err", err)
		return nil, err
	}
	for i, row := range rows {
		if i < 2 {
			continue
		}
		tm := structs.InsurePolicyData{}
		for ii, colCell := range row {
			switch ii {
			case 0:
				tm.No = colCell
			case 1:
				t1, err1 := time.ParseInLocation("2006/01/02 15:04", colCell, time.Local)
				t2, err2 := time.ParseInLocation("2006/1/2 15:04", colCell, time.Local)
				if err1 != nil && err2 != nil {
					continue
				}
				if err1 == nil {
					tm.InsureAt = t1
				}
				if err2 == nil {
					tm.InsureAt = t2
				}
			case 2:
				tm.Holder = colCell
			case 3:
				tm.Phone = colCell
			}
			if !helperx.IsPhone(tm.Phone) {
				continue
			}
		}
		data = append(data, tm)
	}

	return data, nil
}
